<script>
import {mapState} from "vuex";
// 菜单组件，不支持elementUI的menu-item-group
export default {
  name: "SideBar",
  props: {
    collapsed: {
      type: Boolean,
      require: false,
      default: () => false
    }
  },
  methods: {
    menuSelect(active) {
      if (active === this.menuActive) {
        return;
      }
      this.$router.push({path: active})
    },
    createContentOfMenuItem(icon, name, h) { // 渲染菜单项中的图标和文字
      let items = []
      if (icon) {
        items.push(h('i', {class: icon}));
      }
      items.push(h('span', {domProps: {innerHTML: name}}))
      return items;
    },
    createMenuitem(menu, h) { // 渲染一个菜单项
      return h('el-menu-item', {
        key: menu.id,
        props: {index: menu.path,},
        class: ['system-bg-color-horizontal'],
      }, this.createContentOfMenuItem(menu.icon, menu.name, h));
    },
    createMenuItems(menus, h) {
      if (!(menus instanceof Array)) return []; // 如果给的menus是空直接返回空数组
      let menuItemArray = [];
      for (let menu of menus) {
        if (menu.children && menu.children instanceof Array && menu.children.length) { // 子菜单条件判断
          // 构建子菜单
          menuItemArray.push(
            h('el-submenu', {
                props: {index: menu.path},
                class: 'system-bg-color-horizontal'
              }, [
                // 创建子菜单的title插槽
                h('template', {slot: 'title'}, this.createContentOfMenuItem(menu.icon, menu.name, h)),
                ...this.createMenuItems(menu.children, h) // 递归构建子菜单，支持任意级别嵌套菜单
              ]
            )
          );
        } else {
          menuItemArray.push(this.createMenuitem(menu, h)); // 不含子菜单的菜单项
        }
      }
      return menuItemArray;
    }
  },
  computed: {
    collapse: {
      get() {
        return this.collapsed;
      },
      set(v) {
        this.$emit('update:collapsed', v)
      }
    },
    ...mapState('home', ['menuActive', 'menus'])
  },
  render(h) {
    return h('el-menu', {
      class: 'menu',
      props: {defaultActive: this.menuActive, collapse: this.collapse},
      on: {select: this.menuSelect}
    }, this.createMenuItems(this.menus, h))
  }
}
</script>

<style lang="scss" scoped>
.menu {
  height: 100%;
  width: 100%;
}

/*.menu, .menu .el-menu-item {
  background-image: -moz-linear-gradient(LEFT, rgba(44, 44, 44, .3), rgba(111, 111, 111, .2), rgba(44, 44, 44, .3));
  background-image: -webkit-linear-gradient(LEFT, rgba(44, 44, 44, .3), rgba(111, 111, 111, .2), rgba(44, 44, 44, .3));
}*/
</style>